package cz.results.perzist.db4o;


import java.io.*;
import com.db4o.*;
import com.db4o.messaging.*;
import com.db4o.defragment.Defragment;

//TODO predelat server na vlakna
//TODO nacist parametry serveru a konfiguraci z ext. souboru (XML)
//TODO moznost otestovat zda server bezi
public class DbServerDb4o implements MessageRecipient, Runnable{
    private boolean stop = false;
    
    public final static int     PORT=4488;
    public final static String  USER="test";
    public final static String  PSWD="test";
    
    private final static String  YAPF="/home/server/testdb.yap";
    
    public static void main(String[] args) {
        DbConfigDb4o.setDefaultConfig();
        DbServerDb4o runner = new DbServerDb4o();
        runner.run();
    }
    
    
    public void run() {
        synchronized (this) {
            ObjectServer server = Db4o.openServer(YAPF, PORT);
            server.grantAccess(USER, PSWD);
            server.ext().configure().clientServer().setMessageRecipient(this);
            
            try {
                while (!stop) {
                    System.out.println("SERVER:["+System.currentTimeMillis()+"] Server's running....");
                    this.wait(60000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                MessageSender messageSender = server.ext().configure().clientServer().getMessageSender();
                messageSender.send(new StopServer("SERVER is stopping!"));
                server.close();
            }
        }
        
    }
    
    public void processMessage(ObjectContainer con, Object message) {
        synchronized (this) {
            if(message instanceof StopServer) {
                System.out.println("SERVER:" + message);
                stop = true;
                this.notify();
            } else if (message instanceof DefragmentServer) {                System.out.println("SERVER:" + message);
            try {
                Defragment.defrag(YAPF);
                ;
            } catch (IOException ex) {
                System.out.println("SERVER: defragmentace se nezdarila.");
            }
            }
        }
    }
    
}





